<template>
  <div>
    <el-dialog
      title="为用户当前指定角色"
      width="40%"
      :model-value="modelValue"
      @close="closed"
    >
      <el-checkbox-group v-model="checkedRoles">
        <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{
          item.title
        }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closed">关闭</el-button>
          <el-button type="primary" @click="onConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { roleList } from '@/api/role'
import { userRoles, updateRoles } from '@/api/user-manage'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  id: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['update:modelValue', 'updateRole'])

const roles = ref([])
const checkedRoles = ref([])
// 获取所有角色列表
const getRoleLoist = async () => {
  roles.value = await roleList()
}
getRoleLoist()

// 通过id获取当前用户的权限列表
const getUserRoles = async (id) => {
  const { role } = await userRoles(id)
  const ids = role.map((item) => item.id)
  checkedRoles.value = ids
}

watch(
  () => props.id,
  (id) => {
    if (id.length > 0) {
      getUserRoles(id)
    }
  }
)

const closed = () => {
  emits('update:modelValue', false)
}

const onConfirm = async () => {
  const rolesList = roles.value
  const sendRoles = checkedRoles.value.map(id => {
    return rolesList.find(item => item.id === id)
  })
  await updateRoles(props.id, sendRoles)
  ElMessage.success('当前用户角色修改成功')
  emits('updateRole')
  closed()
}
</script>

<style>
</style>
